#include<iostream>
#include<vector>
using namespace std;

class Solution {
public:
    vector<vector<int>> sortMatrix(vector<vector<int>>& grid) {
        vector<int> tmpArr;
        int m = grid.size();
        int count = 2 * m - 1;
        for (int i = 0; i < m; i++) {
            int ci = i; int cj = 0;
            for (int h = i; h < m; h++) {
                tmpArr.push_back(grid[ci][cj]);
                ci++; cj++;
            }
            sort(tmpArr.begin(), tmpArr.end());
            ci = i; cj = 0;
            for (int h = i; h < m; h++) {
                grid[ci][cj] = tmpArr.back();
                ci++; cj++;
                tmpArr.pop_back();
            }
        }
        for (int i = 1; i < m; i++) {
            int ci = 0; int cj = i;
            for (int h = i; h < m; h++) {
                tmpArr.push_back(grid[ci][cj]);
                ci++; cj++;
            }
            sort(tmpArr.begin(), tmpArr.end());
            for (int h = i; h < m; h++) {
                ci--; cj--;
                grid[ci][cj] = tmpArr.back();
                tmpArr.pop_back();
            }
        }
        return grid;
    }
};